/**
 * 
 */
package info.niwota.ziplock.img;

import info.niwota.ziplock.R;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.view.Display;
import android.view.WindowManager;

/**
 * @author qiangli
 * 
 */
public final class BackgroundImages {

	public static final int BG_SELECT_DEFAULT = R.drawable.missing; 


	/**
	 * 
	 */
	private BackgroundImages() {
		// 
	}

	public static String getRandomImage(Context context) {
		String[] proj = new String[] { ImageColumns.DATA };
		Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		Cursor c = null;
		c = context.getContentResolver().query(uri, proj, null, null, null);
		if (!c.moveToFirst()) {
			return null;
		}
		int cnt = c.getCount();
		if (cnt == 0) {
			return null; // no immage?
		}
		Random rand = new Random();
		int pos = rand.nextInt(cnt);
		String p = null;
		try {
			if (c.moveToPosition(pos)) {
				p = c.getString(0);
			}
		} finally {
			c.close();
		}
		return p;
	}
	
	public static void thumbnail(InputStream in, OutputStream out, int width,
			int height) {
		Bitmap image = BitmapFactory.decodeStream(in);
		int w = image.getWidth();
		int h = image.getHeight();
		float scalew = ((float) width) / w;
		float scaleh = ((float) height) / h;
		float scale = Math.min(scalew, scaleh);
		Matrix matrix = new Matrix();
		matrix.postScale(scale, scale);
		Bitmap resized = Bitmap.createBitmap(image, 0, 0, w, h, matrix, true);
		resized.compress(Bitmap.CompressFormat.JPEG, 50, out);
	}
	
	
	/**
	 * Load image scaled if too big with hint of size 200x200
	 * 
	 * @param ctx
	 * @param f
	 * @return
	 */
	public static Drawable loadImage(Context ctx, File f) {
		//320x240
		WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
		Display d = wm.getDefaultDisplay();
		final int width = d.getWidth();
		final int height = d.getHeight();
		//
		String path = f.getPath();
		Options opt = new Options();
		opt.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, opt);
		int w = opt.outWidth;
		int h = opt.outHeight;
		//
		float scalew = w / width;
		float scaleh = h / height;
		int scale = (int) Math.max(scalew, scaleh);
		//
		opt.inJustDecodeBounds = false;
		opt.inSampleSize = scale;
		Bitmap bm = BitmapFactory.decodeFile(path, opt);
		return new BitmapDrawable(bm);
	}
}
